// pages/index/index.js
var plugin = requirePlugin("WechatSI")
var util = require('../../libs/util.js');
var weatherjs = require('../../libs/weather.js');
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var gridColorJs = require('../../libs/index-grid-color.js');
import resource from '../../libs/resource.js'
import {configData} from '../../data/config.js'
// 实例化API核心类'
var qqmapsdk = new QQMapWX({
  key: 'MYDBZ-K4A6P-HCADY-LQOWX-IUBNO-7JFRX'
});

Page({
  data: {
    loading: true,
    grids: [],
    address: {},
    cur_date: '',
    cur_time: '',
    simpleWeather: {},
    header_bg: {
      color: 'white',
      from_color: "#5ABEF9",
      to_color: "#5ABEF9"
    },
    userInfo: {},
    lottie_path: resource.index_lottie_2020_json
  },
  onLoad: function (options) {
    this.getUserInfo()
    this.get_home_data()
    this.getLocationSetting()
    this.progressiveLoad()
  },
  //渐进式加载数据，逐步隐藏 loading
  progressiveLoad() {
    setTimeout(() => {
      this.setData({
        loading: false
      })
    }, 2000)
  },
  onShow: function () {
    var date_time = util.formatDateTime(new Date());
    var date_arr = date_time.split(" ");
    this.setData({
      cur_date: date_arr[0].replace(/-/g, "/"),
      cur_time: date_arr[1]
    });
  },
  onReady() {

  },
  onShareAppMessage() {

  },
  onShareTimeline() {

  },
  openMiniProgram() {
    wx.navigateToMiniProgram({
      appId: 'wx4526fbd058824a3d',
    })
  },
  //获取位置授权等信息
  getLocationSetting() {
    wx.getSetting({
      success: res => {
        //用户位置授权没有开启
        if (!res.authSetting['scope.userLocation']) {
          //申请授权
          wx.authorize({
            scope: 'scope.userLocation',
            success: res => {
              console.log("getLocationSetting-scope.userLocation:授权成功")
              this.get_address_weather(0);
            },
            fail: err => {
              console.log("getLocationSetting-scope.userLocation:授权失败")
              this.get_address_weather(-1)
            }
          })
        } else {
          //授权已开启
          console.log("getLocationSetting-scope.userLocation:授权已开启")
          this.get_address_weather(0);
        }
      },
      fail: err => {
        console.log("调用getSetting失败")
      }
    })
  },
  //获取位置=>天气信息
  get_address_weather(flag, address) {
    console.log('get_address_weather', flag, address)
    switch (flag) {
      case -1: //没有获取到位置信息，直接使用“北京”
        this.get_city_weather('北京')
        break;
      case 0: //获取位置信息
        this.get_location()
        break;
      case 1: //获取天气信息-需要先获取到位置
        this.get_city_weather(address.ad_info.city, address)
        break;
    }
  },
  //获取经纬度信息
  get_location() {
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        console.log("getLocation-success", res)
        this.convert_location(res.latitude, res.longitude);
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  //经纬度转换成地址信息
  convert_location(latitude, longitude) {
    console.log("convert_location", latitude, longitude)
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: res => {
        console.log("convert_location-success", res)
        var address = res.result;
        //获取天气数据
        this.get_address_weather(1, address)
        this.setData({ //设置markers属性和地图位置poi，将结果在地图展示
          address: address
        });
      },
      fail: error => {
        console.log("convert_location-fail", error);
        this.get_address_weather(-1)
      }
    })
  },


  //获取首页配置数据
  get_home_data: function () {
    // getApp().globalData.onling = false
    console.log("get_home_data==", configData)
    let mGrids = configData.filter(item => item.flag == 'home')
    this.setData({
      grids: gridColorJs.getGridWithColor(mGrids)
    })
  },

  //获取城市天气
  get_city_weather(cityInfo, address) {
    var userInfo = this.data.userInfo
    var addressInfo = address != null ? address : {}
    var dateTime = util.formatDateTime(new Date())
    var cityName = cityInfo.replace("市", '')
    console.log('get_city_weather', dateTime, cityName, addressInfo)
    wx.cloud.callFunction({
      name: 'config',
      data: {
        action: 'weather',
        city_name: cityName,
        date_time: dateTime,
        userInfo: userInfo,
        addressInfo: addressInfo
      },
      success: res => {
        console.log('get_city_weather-success', res)
        var resData = res.result;
        this.setData({
          simpleWeather: resData
        })
        this.get_weather_color(resData)
      },
      fail: console.error
    })
  },


  //九宫格点击事件
  onItemClick: function (event) {
    console.log(event)
    let pageUrl = event.detail.cell.url
    if (pageUrl === '') {
      wx.showToast({
        icon: 'none',
        title: '正在开发中！'
      })
    } else {
      wx.navigateTo({
        url: pageUrl,
      })
    }
  },
  //查询天气对应的颜色值
  get_weather_color: function (weather_data) {
    // console.log(weather_data.future[0].wid)
    var wid = weather_data.realtime.wid
    // console.log(wid)
    var weather_color = weatherjs.getWeatherColor(wid)
    // console.log(weather_color)
    //给颜色重新赋值
    var header_bg_new = this.data.header_bg
    if (weather_color.color != null) {
      header_bg_new.color = weather_color.color
    }
    header_bg_new.from_color = weather_color.from_color
    header_bg_new.to_color = weather_color.to_color
    this.setData({
      header_bg: header_bg_new
    })
    var dateStr = util.getNowFormatDate()
    let simpleWeather = this.data.simpleWeather
    this.textSpeech(`当前时间，${dateStr}。今天${simpleWeather.city}天气，
    ${simpleWeather.realtime.info}，气温：${simpleWeather.realtime.temperature}摄氏度`)
  },
  // 获取个人信息
  getUserInfo: function () {
    wx.getUserInfo({
      success: res => {
        console.log("getUserInfo-success", res)
        this.setData({
          userInfo: res.userInfo
        })
        //设置全局的用户信息
        getApp().globalData.userInfo = res.userInfo
      },
      fail: err => {
        console.log("getUserInfo-fail", err)
      }
    })
  },
  //文本合成语音
  textSpeech(text) {
    var _this = this
    plugin.textToSpeech({
      lang: 'zh_CN',
      tts: true,
      content: text,
      success: function (res) {
        console.log("textToSpeech succ tts", res)
        _this.playAudio(res.filename)
      },
      fail: function (res) {
        console.log("textToSpeech fail tts", res)
      }
    })
  },
  //播放音频
  playAudio(audioPath) {
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = audioPath
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
})
